﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands.Waimai
{
    public sealed class ShoppingCartChangeQuantityCommandHandler : BaseCommandHandler, IRequestHandler<ShoppingCartChangeQuantityCommand, BaseResult<string>>
    {
        private readonly IMbrStoreRepository _mbrStoreRepository;
        private readonly IShoppingCartRepository _shoppingCartRepository;
        private readonly IGoodBaseRepository _goodBaseRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mbrStoreRepository"></param>
        /// <param name="goodBaseRepository"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        /// <param name="shoppingCartRepository"></param>
        public ShoppingCartChangeQuantityCommandHandler(IMbrStoreRepository mbrStoreRepository, IGoodBaseRepository goodBaseRepository, INetICService netICService, IHttpClientFactory httpClientFactory,
            IOptionsSnapshot<CasamielSettings> settings, IShoppingCartRepository shoppingCartRepository) : base(netICService, httpClientFactory, settings)
        {
            _mbrStoreRepository = mbrStoreRepository;
            _goodBaseRepository = goodBaseRepository;
            _shoppingCartRepository = shoppingCartRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BaseResult<string>> Handle(ShoppingCartChangeQuantityCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var storeinfo = await _mbrStoreRepository.GetKeyAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
            if (storeinfo == null)
            {
                return new BaseResult<string>(null, 9999, "门店信息有误！");
            }
            if (storeinfo.IsWaimaiClose == 1 || storeinfo.IsWaimaiShopClose==1)
            {
                return new BaseResult<string>(null, 9999, "抱歉门店已闭店！");
            }

            var goodsbase = await _goodBaseRepository.GetDetailV2ByGoodsBaseIdAsync<ICasaMielSession>(request.GoodsBaseId).ConfigureAwait(false);
            if (goodsbase == null)
            {
                return new BaseResult<string>(null, 9999, "产品有误");
            }

            //var listskus = await GetDrinkSkus().ConfigureAwait(false);
            //var a = listskus.Any(c => c.GoodsRelationId == goodsbase.RelationId);
            //if (!a)
            //{
            //    var stockreq = new Domain.Request.ProductStockQueryReq { shopid = storeinfo.RelationId, product = new List<Domain.Request.ProductStockReq>() };
            //    stockreq.product.Add(new Domain.Request.ProductStockReq { pid = $"{goodsbase.RelationId}" });
            //    var ad = await this.NetICService.Productstockquery(stockreq).ConfigureAwait(false);

            //    if (ad.product.Any())
            //    {
            //        if (ad.product[0].count < request.Quantity)
            //        {
            //            var entity = await _shoppingCartRepository.FindAsync<ICasaMielSession>(request.StoreId, request.Mobile, request.GoodsBaseId).ConfigureAwait(false);
            //            if (entity != null)
            //            {
            //                if (entity.GoodsQuantity > request.Quantity)
            //                {
            //                    entity.GoodsQuantity = request.Quantity;
            //                    await _shoppingCartRepository.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
            //                }
            //            }
            //            return new BaseResult<string>(null, 9999, "库存不足");
            //        }
            //    }
            //}

            var url = $"TakeOut/v1/ShoppingCart/ChangeQuantity";
            OrderLogger.Trace($"{JsonConvert.SerializeObject(request)}");
            var result = await PostThirdApiAsync<string>(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);
            return result;
        }
    }
}
